#!/usr/bin/python
# -*- coding=utf-8 -*-

from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
# from django.template import loader
from .models import Book
from .forms import BookForm


# Create your views here.


def index(request):
    text = "<p> hello this is common application</p>"

    return HttpResponse(text)


def pos_arg_request(request, *args):
    text = "<p> positional arguments %s </p>" % (str(args))

    return HttpResponse(text)


def kw_arg_request(request, name, **kwargs):
    text = "<p>keywords arguments name:%s, age:%s</p>" % (name, kwargs.values())

    return HttpResponse(text)


def ctx_data_request(request, **kwargs):
    text = "<p>context arguments %s</p>" % (kwargs.values())

    return HttpResponse(text)


# 使用 shortcut 方法来响应用户请求
def tmp_index_request(request):
    # template = loader.get_template("common/index.html")
    # return HttpResponse(template.render())

    return render(request, "common/index.html")


def book_add(request):
    # Render a page to create a book instance
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/common/book/browse", {"msg": "created book"})
    else:
        form = BookForm()

    return render(request, "common/book/add.html", {"form": form})


def book_browse(request, **kwargs):

    if request.method == "GET":
        books = get_list_or_404(Book)
        context={"books": books}
        if  "msg" in request.GET:
             context["msg"]=request.GET.get("msg")
    elif request.method == "POST":
        search_text = request.POST["search_text"]
        books = Book.objects.filter(name__icontains=search_text)
        context = {"books": books}

    return render(request, "common/book/browse.html", context )


def book_detail(request, book_id):
    # try:
    #     book = Book.objects.get(pk=book_id)
    # except Book.DoesNotExist:
    #     raise Http404("Book does not exists")
    book = get_object_or_404(Book, pk=book_id)

    return render(request, "common/book/detail.html", {"book": book})

